package com.example.runningdemo.designModel.factory.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: Running-Demo
 * @description: cglib代理
 * @author: kangwei
 * @create: 2024-08-11 13:47
 **/
public class CglibProxyHandler implements MethodInterceptor {

    private Object target;

    /**
     * 实现动态代理
     *
     * @param target
     * @return
     */
    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("开启事务");
        Object invoke = method.invoke(target, args);
        System.out.println("关闭事务");
        return invoke;
    }

    public static void main(String[] args) {
        CglibProxyHandler proxyHandler = new CglibProxyHandler();
        UserDao instance = (UserDao) proxyHandler.getInstance(new UserDaoImpl());
        instance.insert();
    }
}
